<script lang="ts" setup>
import { computed } from 'vue'
import { isExternal } from '@/utils/validate'

const props = defineProps({
  name: {
    type: String,
    required: true
  },
  className: {
    type: String,
    default: ''
  }
})
const emit = defineEmits(['click'])

// svg图标名称
const iconNameValue = computed(() => {
  return `#icon-${props.name}`
})
// svg样式
const svgClass = computed(() => {
  if (props.className) {
    return 'svg-icon ' + props.className
  } else {
    return 'svg-icon'
  }
})

// 是否是外部链接
const isExternalValue = computed(() => {
  return isExternal(props.name)
})
// 外部图标样式
const styleExternalIcon = computed(() => {
  return {
    mask: `url(${props.name}) no-repeat 50% 50%`,
    '-webkit-mask': `url(${props.name}) no-repeat 50% 50%`
  }
})
</script>

<template>
  <div
    v-if="isExternalValue"
    :style="styleExternalIcon"
    class="svg-external-icon svg-icon"
    v-bind="$attrs"
    @click="emit('click')"
  />
  <!-- svg：图标外层容器节点，内部配合use使用 -->
  <!-- xlink:href执行用哪一个图标，属性值必须#icon-图标名字 -->
  <svg v-else :class="svgClass" aria-hidden="true" v-bind="$attrs" @click="emit('click')">
    <use :xlink:href="iconNameValue" />
  </svg>
</template>

<style lang="scss" scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.svg-external-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>
